package yun.web.activerecord.dialect.pg;

import yun.web.activerecord.CPI;
import yun.web.activerecord.Model;
import yun.web.activerecord.ModelBuilder;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static yun.web.activerecord.dialect.pg.PGRecordBuilder.buildMap;


/*------------------------
      author: 张天笑
      date: 2019/3/12
      time: 0:11
   规定 rs 对象如何封装成Model
-------------------------*/
public class PGModelBuilder extends ModelBuilder {
    @Override
    public <T> List<T> build(ResultSet rs, Class<? extends Model> modelClass) throws SQLException, ReflectiveOperationException {
        ArrayList result = new ArrayList<T>();
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        String[] labelNames = new String[columnCount + 1];
        int[] types = new int[columnCount + 1];
        this.buildLabelNamesAndTypes(rsmd, labelNames, types);

        while (rs.next()) {
            Model ar = modelClass.newInstance();
            Map<String, Object> attrs = CPI.getAttrs(ar);
            buildMap(attrs, rs, labelNames, columnCount);
            result.add(ar);
        }
        return result;
    }
}
